﻿//-------------------------------------------------------------------------------------------------
// <copyright file="RepositoryHandler.cs" company="Anthony Adam">
// Copyright (c) Anthony Adam 2012. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
// ReSharper disable once CheckNamespace
namespace SuperStarRounds
{
  using System;
  using System.IO;
  using System.Windows.Forms;

  using Classes.FileIO;
  using Localisation;
  using Models;

  /// <summary>
  /// Class containing creation of the file reporitory function and save and load functions on a per tab basis.
  /// </summary>
  public static class RepositoryHandler
  {
    public const string SettingsDirectory = "Settings";
    public const string DockingLayoutFile = "DockingLayout.xml";
    public const string LastUsedContentSettingsFile = "LastUsedContent.cfg";

    /// <summary>
    /// Path to the designer files repository...
    /// </summary>
    public static string DocumentRepository { get; set; }

    /// <summary>
    /// Creates the folder structure under my documents, starting with RPG Designs as the top level.
    /// This is the default path for all save / load of designs.
    /// </summary>
    public static void CreateRepositoryStructure()
    {
      // Ensure our storage area is created in My Documents
      // If the folder already exists, Create Directory silently does nothing :)
      DocumentRepository = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "RPG Designs");
      Directory.CreateDirectory(DocumentRepository);
      Directory.CreateDirectory(Path.Combine(DocumentRepository, "Wondrous Items"));
    }

    public static ContentInclusions LoadLastUsedInclusion()
    {
      var itemLoaded = new ContentInclusions();
      try
      {
        Cursor.Current = Cursors.WaitCursor;
        if (string.IsNullOrWhiteSpace(DocumentRepository)) CreateRepositoryStructure();

        var directory = Path.Combine(DocumentRepository, SettingsDirectory);
        if (!Directory.Exists(directory)) return itemLoaded;

        var file = Path.Combine(DocumentRepository, SettingsDirectory, LastUsedContentSettingsFile);
        if (!File.Exists(file)) return itemLoaded;

        itemLoaded = ContentConfigurationSerializer.DeserializeContentInclusions(file);
        Cursor.Current = Cursors.Default;
      }
      catch (Exception)
      {
        // reset cursor and return default settings if there is a load problem
        Cursor.Current = Cursors.Default;
      }

      return itemLoaded;
    }

    /// <summary>
    /// Load a Wondrous Item Design
    /// </summary>
    /// <returns>The loaded Wondrous Item serialized packet</returns>
    public static WondrousItemSerializedForSaveLoad LoadWondrousItem()
    {
      var itemLoaded = new WondrousItemSerializedForSaveLoad();

      try
      {
        if (string.IsNullOrWhiteSpace(DocumentRepository)) CreateRepositoryStructure();

        var loadFile = new OpenFileDialog
        {
          Title = AdvisorStrings.RepositoryHandler_LoadWondrousItem_Load_Wondrous_Item,
          InitialDirectory = Path.Combine(DocumentRepository, "Wondrous Items"),
          Filter = AdvisorStrings.RepositoryHandler_LoadWondrousItem_Wondrous_Item___itm,
          RestoreDirectory = true
        };

        if (loadFile.ShowDialog() != DialogResult.OK) return itemLoaded;
        if (loadFile.FileName.Equals(string.Empty)) return itemLoaded;

        Cursor.Current = Cursors.WaitCursor;
        itemLoaded = WondrousItemSerializer.DeserializeWondrousItem(loadFile.FileName);
        Cursor.Current = Cursors.Default;
      }
      catch (Exception ex)
      {
        Cursor.Current = Cursors.Default;
        MessageBox.Show(
          AdvisorStrings.RepositoryHandler_LoadWondrousItem_File_Load_Failed__ + ex.Message,
          AdvisorStrings.RepositoryHandler_LoadWondrousItem_Load_Wondrous_Item_Failed,
          MessageBoxButtons.OK, MessageBoxIcon.Error);
      }

      return itemLoaded;
    }

    public static void SaveLastUsedInclusion(ContentInclusions itemToSave)
    {
      string file = null;
      try
      {
        if (string.IsNullOrWhiteSpace(DocumentRepository)) CreateRepositoryStructure();

        var directory = Path.Combine(DocumentRepository, SettingsDirectory);
        file = Path.Combine(DocumentRepository, SettingsDirectory, LastUsedContentSettingsFile);

        Cursor.Current = Cursors.WaitCursor;
        if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
        if (!File.Exists(file)) File.Delete(file);
        ContentConfigurationSerializer.SerializeContentInclusions(file, itemToSave);
        Cursor.Current = Cursors.Default;
      }
      catch (Exception)
      {
        // remove corrupt settings and allow defaults for next load.
        if (!string.IsNullOrWhiteSpace(file))
          if (!File.Exists(file)) File.Delete(file);

        Cursor.Current = Cursors.Default;
      }
    }

    /// <summary>
    /// Save Wondrous Item Design
    /// </summary>
    /// <param name="filenameSansExtension">Name of file to save to without file extension</param>
    /// <param name="itemToSave">The Wondrous Item serialized packet to be saved</param>
    public static void SaveWondrousItem(string filenameSansExtension, WondrousItemSerializedForSaveLoad itemToSave)
    {
      try
      {
        if (string.IsNullOrWhiteSpace(DocumentRepository)) CreateRepositoryStructure();

        var saveFile = new SaveFileDialog
        {
          Title = AdvisorStrings.RepositoryHandler_SaveWondrousItem_Save_Wondrous_Item,
          InitialDirectory = Path.Combine(DocumentRepository, "Wondrous Items"),
          Filter = AdvisorStrings.RepositoryHandler_LoadWondrousItem_Wondrous_Item___itm,
          FileName = filenameSansExtension + ".itm"
        };


        if (saveFile.ShowDialog() != DialogResult.OK) return;
        if (saveFile.FileName.Equals(string.Empty)) return;

        Cursor.Current = Cursors.WaitCursor;
        WondrousItemSerializer.SerializeWondrousItem(saveFile.FileName, itemToSave);
        Cursor.Current = Cursors.Default;
      }
      catch (Exception ex)
      {
        Cursor.Current = Cursors.Default;
        MessageBox.Show(
          AdvisorStrings.RepositoryHandler_SaveWondrousItem_File_Save_Failed__ + ex.Message,
          AdvisorStrings.RepositoryHandler_SaveWondrousItem_Save_Wondrous_Item_Failed,
          MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
  }
}
